package com.dongliu.controller;

import com.dongliu.domain.Admin;
import com.dongliu.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping
    public Result save(@RequestBody Admin admin) {
        System.out.println(admin);
        boolean flag = adminService.save(admin);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Admin admin) {
        boolean flag = adminService.update(admin);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = adminService.delete(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        System.out.println(admin);
        Integer code = admin != null ? Code.GET_OK : Code.GET_ERR;
        String msg = admin != null ? "" : "数据查询失败，请重试！";
        return new Result(code, admin, msg);
    }

    @GetMapping
    public Result getAll(HttpServletRequest request) {
        Admin a = (Admin) request.getSession().getAttribute("admin");
        if(a == null)
            return new Result(Code.LOGIN_ERR, null, "请登录后再执行操作！");
        List<Admin> adminList = adminService.getAll();
        Integer code = adminList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = adminList != null ? "":"数据查询失败，请重试！";
        return new Result(code, adminList, msg);
    }
}
